/* 
 * av Morten Calsson
 * Not yet implemented
 */

$(document).ready(function() {
    var geocoder = new google.maps.Geocoder();
    var total;
    var progress = 0;
    var failList;
    var list;
    var BARS;
    var RESULT;
    var missing_list = [];

    prepareGetBarsWithoutGeolocation();
    bind();

    function bind() {
        $("#getGeoLocBtn").unbind("click").bind("click", function() {
            $("#getGeoLocBtn").hide();
            list = [];
            failList = [];
            $("#missingTable").show();
            $.when(getBarsWithoutGeolocation()).then(function(result) {
                BARS = result;
                for (var i = 0; i < result.length; i++) {
                    list.push(result[i].address + "," + result[i].postal_no + " " + result[i].place);
                }
                setUpGetGeoLocation();
            });

        });
        $("#reFetchGeoLocBtn").unbind("click").bind("click", function() {
            setUpGetGeoLocation();
        });
    }
    function prepareGetBarsWithoutGeolocation() {
        list = [];
        failList = [];
        $.when(getBars()).then(function(result) {
            var ret = "";
            BARS = result;
            console.log(BARS);
            var numberOfBarsWithoutGeoLoc = result.length;
            if (numberOfBarsWithoutGeoLoc > 0) {
                $("#updateInfo").html(numberOfBarsWithoutGeoLoc + " Bars Without Geo Locations");
//                $("#missingTable").slideDown("slow");
                $("#missingTable").css("opacity", "0").css("width", "10%").animate({
                    display: "block",
                    width: "40%",
                    opacity: 1
                }, "slow");
            } else{
                $("#updateInfo").html("No Bars Without Geo Locations").css("color", "orange");
            }
            for (var i = 0; i < numberOfBarsWithoutGeoLoc; i++) {
                ret += "<tr><td>" + result[i].name + "</td><td>" + result[i].address + ", " + result[i].postal_no + " " + result[i].place + "</td></tr>";
            }
            for (var i = 0; i < result.length; i++) {
                list.push(result[i].address + "," + result[i].postal_no + " " + result[i].place);
            }
            $("#missingTable").append(ret);
        });
    }
    function setUpGetGeoLocation() {
        total = list.length;
        var getLocation = function(address) {
            $.when(getGeoLocation(address)).then(function(result) {
                var percent = ((progress / total) * 100);
                var ret = "Hentet <b>" + progress + "</b> av <b>" + total + "</b> (" + percent + " %).";
                $("#updateInfo").html(ret);
                $("#resultTable").append("<tr><td>" + progress + "</td><td>" + BARS[progress - 1].name + "</td><td>" + list[progress - 1] + "</td><td>" + result + "</td></tr>");

                $.when(saveGeoLocationToDB({barid: BARS[progress - 1].bar_id, latlong: result})).then(function() {
                    if (progress <= total-1) {
                        setTimeout(function() {
                            getLocation(list[progress]);
                        }, 1000);
                    } else {
                        if (failList.length > 0) {
                            var ret = "<span style='color:black;font-size:16px;'>Kunne ikke hente geo lokasjon for disse barene:</span> <br/>";
                            for (var i = 0; i < failList.length; i++) {
                                ret += "- " + failList[i] + ".<br/>";
                            }
                            $("#failList").html(ret);
                        }
                    }
                });
            }).fail(function(result) {
                failList.push(result);
                var ret = "Kunne ikke hente geo lokasjon for disse barene: <br/>";
                ret += "- " + result + ".<br/>";
                $("#failList").append(ret);
                if (progress < total) {
                    setTimeout(function() {
                        getLocation(list[progress]);
                    }, 1000);
                }
            });
        };
        $("#missingTable").hide();
        $("#resultTable").show();
        $("#reFetchGeoLocBtn").hide();
        $("#getGeoLocBtn").hide();
        $("#headerMissing").hide();
        getLocation(list[0]);
    }
    function getGeoLocation(addressData) {
        var dfd = new $.Deferred();
        geocoder.geocode({
            'address': addressData
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var result = results[0].geometry.location;
                progress++
                dfd.resolve(result);
            } else {
                progress++
                dfd.reject(addressData);
            }
        });
        return dfd.promise();
    }

    function getBars() {
        var dfd = new $.Deferred();
        $.ajax({
            type: "GET",
            url: "../resources/helpers/getBarsWithoutGeolocation.php",
            data: {
                action: 'getBarsWithoutGeolocation'
            },
            cache: false,
            success: function(data)
            {
                data = JSON.parse(data);
                dfd.resolve(data);
            }
        });
        return dfd.promise();
    }


    function getBarsWithoutGeolocation() {
        var dfd = new $.Deferred();
        $.ajax({
            type: "GET",
            url: "../resources/helpers/getBarsWithoutGeolocation.php",
            data: {
                action: 'getBarsWithoutGeolocation'
            },
            cache: false,
            success: function(data)
            {
                data = JSON.parse(data);
                dfd.resolve(data);
            }
        });
        return dfd.promise();
    }

    function saveGeoLocationToDB(args) {
        var dfd = new $.Deferred();
        $.ajax({
            type: "POST",
            url: "../resources/helpers/updateGeoLocation.php",
            data: {
                action: 'updateGeoLocation',
                barid: args.barid,
                geoLocation: args.latlong.toString()
            },
            cache: false,
            success: function(data)
            {
                console.log(data);
                dfd.resolve();
            }
        });
        return dfd.promise();
    }



});